<!-- @author wuyuliang -->
<template>
  <ul class="right-menu" :show="isHidden" :style="rightMenuStyle">
    <!-- <a href="javascript:;" v-for="(item, index) in menus" :key="index" @click="click(item)">{{item.menuName}}</a> -->
    <li class="menu-item" data-item="0" v-for="(item, index) in menus" :key="index" @click="click(item)">
      &nbsp;<i :class="item.icon ? item.icon : 'el-icon-edit'" data-item="0"></i>&nbsp; {{item.menuName}}
    </li>
  </ul>
</template>

<script>
export default {
  name: 'rightMenu',
  props: {
    // 菜单附着的对象，使用dom选择器来解析
    target: {
      type: String
    },
    // 菜单配置项
    menus: {
      type: Array,
      required: true
    }
  },
  mounted () {
    let targetA = this.$(this.target)[0]
    // 右键显示菜单
    targetA.oncontextmenu = ($event) => {
      let obj = $event.srcElement ? $event.srcElement : $event.target;
      this.attachTarget = obj;
      // 改变菜单的位置
      this.rightMenuStyle.left = $event.clientX + 'px';
      this.rightMenuStyle.top = $event.clientY + 'px';
      // 显示菜单
      this.rightMenuStyle.display = 'flex';
      //防止默认菜单弹出
      $event.preventDefault();
    }
    // 点击其他位置隐藏菜单
    document.onclick = ($event) => {
      this.rightMenuStyle.display = 'none';
    }
  },
  data () {
    return {
      // 右键菜单
      isHidden: true,
      rightMenuStyle: { top: '0px', left: '0px', display: 'none' },
      attachTarget: null
    }
  },
  methods: {
    click (menu) {
      this.$emit(menu.click ? menu.click : 'click', this.attachTarget, menu);
    },
    $ (e) {
      let eType = 'queryeAll'
      if (e.indexOf('#') === 0) {
        eType = 'getElementById'
        e = e.substr(1, e.length)
      }
      if (e.indexOf('.') === 0) {
        eType = 'getElementsByClassName'
        e = e.substr(1, e.length)
      }
      return document[eType](e)
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.right-menu {
  flex-direction: column;
  position: absolute;
  min-width: 128px;
  width: auto;
  z-index: 9999;
  font-family: 微软雅黑;
  font-size: 14px;
  background-color: rgb(255, 255, 255);
  box-sizing: border-box;
  box-shadow: rgba(0, 0, 0, 0.1) 0px 4px 12px;
  list-style: none;
  padding: 5px 0px;
  margin: 0px;
  border-width: 1px;
  border-style: solid;
  border-color: rgba(0, 0, 0, 0.15);
  border-image: initial;
  border-radius: 4px;
  list-style: none;
  .menu-item {
    padding: 10px;
    text-decoration: none;
    cursor: pointer;
  }
  .menu-item:hover {
    color: white;
    background: #343a40;
  }
}
</style>
